package com.expensetracker;

import java.util.Date;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.expensetracker.dto.ExpenseTransaction;
import com.expensetracker.dao.hibernate.HibernateUtil;
import com.expensetracker.dto.Expense;
import com.expensetracker.dto.ExpenseType;
import com.expensetracker.dto.PlaceOfPurchase;

import com.expensetracker.dto.User;

public class ExpenseTrackerMain {
	public static void main(String args[]) {
		PlaceOfPurchase place;
		User user;
		ExpenseType expenseType;
		Session session = HibernateUtil.getSession();
		Transaction tx = session.beginTransaction();
		try {
//			book = (Book) session.load(Book.class, new Long(1));
			//place = (PlaceOfPurchase) session.load(PlaceOfPurchase.class, new Long(300));
//			place = (PlaceOfPurchase) session.get(PlaceOfPurchase.class, new Long(300));
//			place = new PlaceOfPurchase();
//			place.setName("Wal-Mart Dartmouth");
//			place.setTitle("Wal-Mart Dartmouth");
//			place.setDescription("Wal-Mart");
//			place.setLocation("location");
			
//			session.save(place);
			
//			ExpenseType parent = (ExpenseType) session.load(ExpenseType.class, new Long(1));
//			
//			
//			expenseType = new ExpenseType();
//			
//			expenseType.setName("Food");
//			expenseType.setDescription("Things to eat");
//			expenseType.setParent(parent);
//			
//			session.save(expenseType);
			
			user = (User) session.load(User.class, new Long(50));
			place = (PlaceOfPurchase) session.load(PlaceOfPurchase.class, new Long(300));
			expenseType = (ExpenseType) session.load(ExpenseType.class, new Long(950));
			
			ExpenseTransaction transaction = new ExpenseTransaction();
			transaction.setPurchaseDate(new Date());
			transaction.setPlaceOfPurchase(place);
			transaction.setUser(user);
			
			Expense expense1 = new Expense();
			expense1.setAmount(new Double(500.00));
			expense1.setTransaction(transaction);
			expense1.setExpenseType(expenseType);
			
			Expense expense2 = new Expense();
			expense2.setAmount(new Double(500.00));
			expense2.setTransaction(transaction);
			expense2.setExpenseType(expenseType);
			
			transaction.getExpenses().add(expense1);
			transaction.getExpenses().add(expense2);
			
			session.save(transaction);
					
			tx.commit();
		} catch (HibernateException e) {
			e.printStackTrace();
//			e.getCause().printStackTrace();
			if (tx != null)
				tx.rollback();
			throw e;
		} finally {
			session.close();
		}
		
//		System.out.println("Title: " + place.getTitle());
	}
}
